package com.tdu.spider.biz.service.xclient;

import com.google.common.collect.Lists;
import com.tdu.spider.dao.XclientInfoDORepository;
import com.tdu.spider.dao.XclientVersionRepository;
import com.tdu.spider.model.XclientInfoDO;
import com.tdu.spider.model.XclientVersionDO;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class XclientService {
    private static Logger           logger = LoggerFactory.getLogger(XclientService.class);

    @Autowired
    private XclientInfoDORepository xclientInfoDORepository;

    @Autowired
    private XclientVersionRepository xclientVersionRepository;

    public boolean batch() throws Exception {
        for (int i = 1; i < 36; i++) {
            Response response = Request.Get("http://xclient.info/s/" + i)
                .addHeader("Cookie",
                    "PHPSESSID=ie66tio9a11sfp09dh8qtf7bq7; Hm_lvt_befb95b3cbb10a937d15e5181625c9f2=1495156916,1495431892,1496358424,1496639664; Hm_lpvt_befb95b3cbb10a937d15e5181625c9f2=1496883017")
                .userAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
                .execute();
            Document document = Jsoup.parse(response.returnContent().asString());
            Elements elements = document.select("ul.post_list li");

            List<XclientInfoDO> xclientInfoDOS = Lists.newArrayList();
            for (Element element : elements) {
                XclientInfoDO xclientInfoDO = new XclientInfoDO();

                xclientInfoDO.setContent(element.select("div.info p").text());
                xclientInfoDO.setDownLoadNum(
                    Integer.valueOf(element.select("div.status_bar span.download").text()));
                xclientInfoDO.setTitle(element.select("a[title]").attr("title"));
                xclientInfoDO.setCates(element.select("div.cates").text());
                xclientInfoDO.setCatesLink(element.select("div.cates a").attr("href"));
                xclientInfoDO.setUpdateDate(element.select("div.status_bar span.date").text());
                xclientInfoDO.setImg(element.select("img.lim-icon").attr("src"));
                xclientInfoDO.setUrl(element.select("a[title]").attr("href"));
                String id = xclientInfoDO.getUrl().substring(
                    xclientInfoDO.getUrl().lastIndexOf("/") + 1,
                    xclientInfoDO.getUrl().lastIndexOf("."));
                xclientInfoDO.setId(id + "_" + UUID.randomUUID().toString());
                xclientInfoDOS.add(xclientInfoDO);
            }
            xclientInfoDORepository.saveAll(xclientInfoDOS);
        }
        return false;
    }

    public boolean batchVersion() throws Exception {
        List<XclientInfoDO> xclientInfoDOS = xclientInfoDORepository.findAll();
        List<XclientVersionDO> xclientVersionDOS=Lists.newArrayList();
        for (XclientInfoDO xclientInfoDO : xclientInfoDOS) {
            logger.info("spider----{}---", xclientInfoDO.getUrl());

            XclientVersionDO xclientVersionDO = new XclientVersionDO();
            xclientVersionDO.setInfoId(xclientInfoDO.getId());
            Response response = Request.Get(xclientInfoDO.getUrl())
                .addHeader("Referer", "http://xclient.info/s/34/")
                .addHeader("Cookie",
                    "PHPSESSID=ie66tio9a11sfp09dh8qtf7bq7; Hm_lvt_befb95b3cbb10a937d15e5181625c9f2=1495156916,1495431892,1496358424,1496639664; Hm_lpvt_befb95b3cbb10a937d15e5181625c9f2=1496883017")
                .userAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
                .execute();
            Document document = Jsoup.parse(response.returnContent().asString());
            Elements link = document.select("div.history_version tbody tr").eq(0);
            xclientVersionDO.setVersion(link.select("td.version_num").text());
            xclientVersionDO
                .setViewNum(Integer.valueOf(document.select("ul.post-meta li").eq(2).text()));
            xclientVersionDO.setUpdateDate(link.select("td").eq(2).text());
            xclientVersionDO.setSize(link.select("td").eq(3).text());

            String lastVersionUrl=link.select("i.icon-disk-baidu").parents().attr("href");
            if(StringUtils.isNotBlank(lastVersionUrl)) {
                lastVersionUrl=lastVersionUrl.replaceAll(" ","%20");
                baidu(xclientVersionDO, xclientInfoDO.getUrl(), lastVersionUrl);
            }else{
                xclientVersionDO.setOfficialUrl(document.select("div.download_btns div.btn_wrap a").attr("href"));
            }
            Elements elements = document.select("div.post-content h2");
            for (Element element : elements) {
                if (element.text().contains("应用介绍")) {
                    Element next = element.nextElementSibling();
                    if (!next.nodeName().equals("h2")) {
                        xclientVersionDO.setAppDesc(next.text());
                    }
                } else if (element.text().contains("更新日志")) {
                    Element next = element.nextElementSibling();
                    if (!next.nodeName().equals("h2")) {
                        xclientVersionDO.setUpdateLog(next.text());
                    }
                } else if (element.text().contains("安装方法")) {
                    Element next = element.nextElementSibling();
                    if (!next.nodeName().equals("h2")) {
                        xclientVersionDO.setActiveDesc(next.text());
                    }
                } else if (element.text().contains("激活方法")) {
                    Element next = element.nextElementSibling();
                    if (!next.nodeName().equals("h2")) {
                        xclientVersionDO.setActiveDesc(next.text());
                    }
                }
            }
            xclientVersionDOS.add(xclientVersionDO);
        }
        xclientVersionRepository.saveAll(xclientVersionDOS);
        return true;
    }

    public void baidu(XclientVersionDO xclientVersionDO, String referer,
                      String url) throws Exception {
        logger.info("referer:{}---url:{}",referer,url);
        Response response = Request.Get(url).addHeader("Referer", referer)
            .addHeader("Cookie",
                "PHPSESSID=ie66tio9a11sfp09dh8qtf7bq7; Hm_lvt_befb95b3cbb10a937d15e5181625c9f2=1495156916,1495431892,1496358424,1496639664; Hm_lpvt_befb95b3cbb10a937d15e5181625c9f2=1496883017")
            .userAgent(
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
            .execute();
        Document document = Jsoup.parse(response.returnContent().asString());
        String link = document.select("a.btn_down_link").attr("data-link");
        String pwd = document.select("a.btn_down_link").attr("data-clipboard-text");
        xclientVersionDO.setBaiduLink(link);
        xclientVersionDO.setBaiduPwd(pwd);
    }

    public boolean update() throws Exception {
        return false;
    }
}
